package com.ccmusic.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ccmusic.Message.Msg;
import com.ccmusic.entity.Matching;
import com.ccmusic.entity.Music;
import com.ccmusic.service.MatchingService;
import com.ccmusic.service.MusicService;
import com.ccmusic.service.SingerService;
import com.ccmusic.service.impl.MatchingServiceImpl;
import com.ccmusic.service.impl.MusicServiceImpl;
import com.ccmusic.service.impl.SingerServiceImpl;
import com.ccmusic.util.DatatablesBean;
import com.google.gson.Gson;

/**
 * Music/音乐Servlet 可用接口 /MusicServlet /ms.do Author zhujz
 * 
 * Servlet implementation class MusicServelt
 */
@WebServlet({ "/MusicServelt", "/ms.do" })
public class MusicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MusicService ms = new MusicServiceImpl();
	private SingerService ss = new SingerServiceImpl();
	private MatchingService matchingService = new MatchingServiceImpl();

	/**
	 * Default constructor.
	 */
	public MusicServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String ac = request.getParameter("ac");
		if ("query".equals(ac)) {
			doGetMusics(request, response);
		} else if ("add".equals(ac)) {
			doAddMusic(request, response);
		} else if ("del".equals(ac)) {
			doDelMusic(request, response);
		} else if ("update".equals(ac)) {
			doUpdateMusic(request, response);
		} else if ("like".equals(ac)) {
			doLike(request, response);
		} else if ("collect".equals(ac)) {
			/**
			 * 4.2--wwb 新增收藏功能
			 */
			//System.out.println(ac);
			doCollect(request, response);
		}else if("searchMid".equals(ac)) {
			searchMid(request, response);
		}

	}

	protected void searchMid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		
		String url=request.getParameter("musicId");
		int uid=Integer.parseInt(request.getParameter("uid"));
		
		Music music=ms.getMusicByMid(url);
		boolean result=false;
		if(music!=null) {
			int mid=music.getMid();
			//Matching matching=new Matching(uid, mid);
			
			result=matchingService.getMatching(uid, mid);
		}else {
			System.out.println("添加了音乐");
			String mname=request.getParameter("mname");
			Music mu=new Music(mname, url);
			ms.addMusic(mu);
			Music music1=ms.getMusicByMid(url);
			int mid=music1.getMid();
			//Matching matching=new Matching(uid, mid);
			
			result=matchingService.getMatching(uid, mid);
		}
		
		Msg mess=new Msg();
		
		if(result) {
			mess.setMsg("已收藏");
		}else {
			mess.setMsg("收藏");
		}
		
		Gson gson=new Gson();
		PrintWriter out=response.getWriter();
		out.print(gson.toJson(mess));
		out.close();
	}

	protected void doCollect(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		
		String op=request.getParameter("op");
		int uid=Integer.parseInt(request.getParameter("uid"));
		
		
		
		String url=request.getParameter("url");
		//String mname=request.getParameter("mname");
		Music music=ms.getMusicByMid(url);
		int mid=music.getMid();
		//System.out.println(mid+"我是mid");
		Matching matching=new Matching(uid,mid);
		
		boolean result =false;
		
		Gson gson=new Gson();
		PrintWriter out=response.getWriter();
		Msg mess=new Msg();
		
		if("collect".equals(op)) {
			result = matchingService.addMatching(matching);			
		}else {
			result = matchingService.removeMatching(matching);
		}
		
		if(result) {
			mess.setOk(true);
		}else {
			mess.setOk(false);
		}
		
		out.print(gson.toJson(mess));
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * 响应ajax请求，获取所有音乐并以Json数据类型格式把获得的结果返回给前端ajax。
	 * 
	 * @param request
	 *            请求
	 * @param response
	 *            响应
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doGetMusics(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		List<Music> list = ms.getAllMusic();
		DatatablesBean<Music> dtb = new DatatablesBean<>(list);
		Gson gson = new Gson();
		PrintWriter pw = response.getWriter();
		pw.print(gson.toJson(dtb));
		pw.close();

	}

	/**
	 * 新增音乐
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doAddMusic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		String mname = request.getParameter("mname");
		String url = request.getParameter("murl");
		Gson gson = new Gson();
		Msg msg = new Msg();
		if (mname != null && (!mname.equals("")) && url != null || (!url.equals(""))) {
			if (ms.addMusic(new Music(mname, url))) {
				msg.setMsg("添加成功！");
			} else {
				msg.setMsg("添加失败");
			}
		} else {
			msg.setMsg("添加失败！");
		}
		PrintWriter pw = response.getWriter();
		pw.print(gson.toJson(msg));
		pw.close();

	}

	/**
	 * 删除音乐
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doDelMusic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		String mid = request.getParameter("mid");
		//System.out.println(mid);
		Gson gson = new Gson();
		Msg msg = new Msg();
		if (!mid.equals("")) {
			int imid = Integer.parseInt(mid);
			try {
				ss.delSingerByMid(mid);
				matchingService.delMatchingByMid(mid);
				if (ms.deleteMusicByMid(imid)) {
					msg.setMsg("删除成功！");
				} else {
					msg.setMsg("删除失败");
				}
			} catch (Exception e) {
				System.out.println("删除异常！");
			}
		} else {
			msg.setMsg("删除失败！");
		}
		PrintWriter pw = response.getWriter();
		pw.print(gson.toJson(msg));
		pw.close();

	}

	/**
	 * 更新音乐名和url
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doUpdateMusic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		String mid = request.getParameter("mid");
		//System.out.println(mid);
		int imid = Integer.parseInt(mid);
		String mname = request.getParameter("newMname");
		String url = request.getParameter("newUrl");
		Music music = new Music(imid, mname, url);
		Gson gson = new Gson();
		Msg msg = new Msg();
		if (mname != null && (!mname.equals("")) && url != null || (!url.equals(""))) {
			if (ms.updateMusic(music)) {
				msg.setMsg("更新成功！");
			} else {
				msg.setMsg("更新失败");
			}
		} else {
			msg.setMsg("更新失败！");
		}
		PrintWriter pw = response.getWriter();
		pw.print(gson.toJson(msg));
		pw.close();

	}

	protected void doLike(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置响应编码
		response.setCharacterEncoding("utf-8");
		// 设置响应数据类型
		response.setContentType("application/json");
		String mid = request.getParameter("id");
		String op = request.getParameter("op");
		String name = request.getParameter("name");
		Gson gson = new Gson();
		Msg msg = new Msg();
		if ("like".equals(op)) {
			if (ms.getMusicByMid(mid) != null) {
				if (ms.likeIt(mid))
					msg.setOk(true);
				else
					msg.setOk(false);
			} else {
				if (ms.addMusic(new Music(0, name, 1, mid, 0, 0)))
					msg.setOk(true);
				else
					msg.setOk(false);
			}
		} else if ("dislike".equals(op)) {
			if (ms.getMusicByMid(mid) != null) {
				if (ms.dislikeIt(mid))
					msg.setOk(true);
				else
					msg.setOk(false);
			}
		}
		PrintWriter pw = response.getWriter();
		pw.print(gson.toJson(msg));
		pw.close();

	}

}
